<?php

namespace app\api\model;

use think\Model;
use app\api\model\OrderProduct as OrderProductModel;

class Order extends Base
{
    protected $autoWriteTimestamp = true;
    protected $hidden = ['delete_time'];

    /**
     * 读取器，格式化字段
     * @param $value
     * @return array|mixed
     */
    public function getSnapItemsAttr($value)
    {
        if (empty($value))
        {
            return [];
        }

        return json_decode($value);
    }

    /**
     * 读取器，格式化字段
     * @param $value
     * @return array|mixed
     */
    public function getSnapAddressAttr($value)
    {
        if (empty($value))
        {
            return [];
        }

        return json_decode($value);
    }

    /**
     * 创建订单快照
     * @param $user_id
     * @param $snapOrder
     * @return array
     */
    public static function createSnapOrder($user_id, $snapOrder, $orderProducts)
    {
        try
        {
            $arr = [
                'user_id'      => $user_id,
                'order_no'     => $snapOrder['order_no'],
                'total_price'  => $snapOrder['totalPrice'],
                'total_count'  => $snapOrder['totalCount'],
                'snap_img'     => $snapOrder['snapImg'],
                'snap_name'    => $snapOrder['snapName'],
                'snap_address' => json_encode($snapOrder['snapAddress']),
                'snap_items'   => json_encode($snapOrder['snapItems']),

            ];

            $order = self::create($arr);

            // 创建订单 - 商品中间表，记录所需数据
            $orderProductModel = new OrderProductModel();
            $orderProductModel->createOrderUnionProduct($order->id, $orderProducts);

            return [
                'order_id'    => $order->id,
                'order_no'    => $snapOrder['order_no'],
                'create_time' => $order->create_time,
            ];
        }
        catch (Exception $ex)
        {
            throw $ex;
        }
    }

    /**
     * 根据用户ID获取订单列表
     * @param $uid
     * @param int $page
     * @param int $size
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getListByUser($uid, $page = 1, $size = 15)
    {
        $pagingData = self::where('user_id', '=' ,$uid)
            ->order('create_time desc')
            ->paginate($size, false, ['page' => $page]);
        $pagingData->hidden(['snap_items', 'update_time', 'prepay_id', 'snap_address']);
        return $pagingData;
    }
}
